class Tetris {
    constructor(canvas) {
        this.ctx = canvas.getContext('2d');
        this.grid = Array(20).fill().map(() => Array(10).fill(0));
        this.blockSize = 30;
        this.currentPiece = null;
        this.score = 0;
        this.level = 1;
        this.linesCleared = 0;
        this.gameSpeed = 1000;
        this.gameLoop = null;
        this.isPaused = false; // 新增暂停状态
        
        // 七种经典方块形状
        this.shapes = [
            [[1,1,1,1]], // I
            [[1,1],[1,1]], // O
            [[1,1,1],[0,1,0]], // T
            [[1,1,1],[1,0,0]], // L
            [[1,1,1],[0,0,1]], // J
            [[1,1,0],[0,1,1]], // S
            [[0,1,1],[1,1,0]]  // Z
        ];
    }

    newPiece() {
        const shape = this.shapes[Math.floor(Math.random() * this.shapes.length)];
        this.currentPiece = {
            shape,
            x: Math.floor((10 - shape[0].length)/2),
            y: 0,
            color: `hsl(${Math.random()*360}, 70%, 50%)`
        };
        
        if (this.collision()) {
            alert('游戏结束！');
            clearInterval(this.gameLoop);
        }
    }

    collision() {
        return this.currentPiece.shape.some((row, dy) => {
            return row.some((cell, dx) => {
                if (!cell) return false;
                const nx = this.currentPiece.x + dx;
                const ny = this.currentPiece.y + dy;
                return nx < 0 || nx >= 10 || ny >= 20 || this.grid[ny]?.[nx];
            });
        });
    }

    rotate() {
        const rotated = this.currentPiece.shape[0].map((_, i) =>
            this.currentPiece.shape.map(row => row[i]).reverse()
        );
        const oldShape = this.currentPiece.shape;
        this.currentPiece.shape = rotated;
        if (this.collision()) {
            this.currentPiece.shape = oldShape;
        }
    }

    clearLines() {
        let lines = 0;
        this.grid = this.grid.filter(row => {
            if (row.every(cell => cell)) lines++;
            return !row.every(cell => cell);
        });
        
        while (this.grid.length < 20) {
            this.grid.unshift(Array(10).fill(0));
        }

        if (lines > 0) {
            this.linesCleared += lines;
            this.score += lines * 100 * this.level;
            document.getElementById('score').textContent = this.score;
            
            if (this.linesCleared >= 10) {
                this.level++;
                this.gameSpeed *= 0.8;
                this.linesCleared -= 10;
                document.getElementById('level').textContent = this.level;
                clearInterval(this.gameLoop);
                this.gameLoop = setInterval(() => this.update(), this.gameSpeed);
            }
        }
    }

    lockPiece() {
        this.currentPiece.shape.forEach((row, dy) => {
            row.forEach((cell, dx) => {
                if (cell) {
                    this.grid[this.currentPiece.y + dy][this.currentPiece.x + dx] = this.currentPiece.color;
                }
            });
        });
        this.clearLines();
    }

    update() {
        this.currentPiece.y++;
        if (this.collision()) {
            this.currentPiece.y--;
            this.lockPiece();
            this.newPiece();
        }
        this.draw();
    }

    // 在draw方法中添加
    draw() {
        this.ctx.fillStyle = '#2c3e50';
        this.ctx.fillRect(0, 0, 300, 600);
        
        // 绘制网格
        this.grid.forEach((row, y) => {
            row.forEach((color, x) => {
                if (color) {
                    this.ctx.fillStyle = color;
                    this.ctx.fillRect(x * this.blockSize, y * this.blockSize, this.blockSize-1, this.blockSize-1);
                }
            });
        });

        // 绘制当前方块
        if (this.currentPiece) {
            this.ctx.fillStyle = this.currentPiece.color;
            this.currentPiece.shape.forEach((row, dy) => {
                row.forEach((cell, dx) => {
                    if (cell) {
                        this.ctx.fillRect(
                            (this.currentPiece.x + dx) * this.blockSize,
                            (this.currentPiece.y + dy) * this.blockSize,
                            this.blockSize-1,
                            this.blockSize-1
                        );
                    }
                });
            });
        }
        // 绘制暂停状态
        if (this.isPaused) {
            this.ctx.fillStyle = 'white';
            this.ctx.font = '24px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText('暂停中', 150, 300);
        }
    }
}

// 初始化游戏
const canvas = document.getElementById('gameCanvas');
const game = new Tetris(canvas);
const pauseButton = document.getElementById('pauseButton');

// 添加暂停按钮点击事件
pauseButton.addEventListener('click', () => {
    game.isPaused = !game.isPaused;
    if (game.isPaused) {
        clearInterval(game.gameLoop);
        pauseButton.textContent = '继续';
    } else {
        game.gameLoop = setInterval(() => game.update(), game.gameSpeed);
        pauseButton.textContent = '暂停';
    }
    game.draw();
});

document.addEventListener('keydown', (e) => {
    if (!game.currentPiece) return;
    
    switch(e.key) {
        case 'ArrowLeft':
            game.currentPiece.x--;
            if (game.collision()) game.currentPiece.x++;
            break;
        case 'ArrowRight':
            game.currentPiece.x++;
            if (game.collision()) game.currentPiece.x--;
            break;
        case 'ArrowDown':
            game.currentPiece.y++;
            if (game.collision()) game.currentPiece.y--;
            break;
        case 'ArrowUp':
            game.rotate();
            break;
        case ' ': // 空格键快速下落
            while(!game.collision()) {
                game.currentPiece.y++;
            }
            game.currentPiece.y--;
            game.lockPiece();
            game.newPiece();
            break;
        case 'p':
        case 'P':
            game.isPaused = !game.isPaused;
            if (game.isPaused) {
                clearInterval(game.gameLoop);
                pauseButton.textContent = '继续';
            } else {
                game.gameLoop = setInterval(() => game.update(), game.gameSpeed);
                pauseButton.textContent = '暂停';
            }
            game.draw();
            break;
    }
    game.draw();
});

game.newPiece();
game.gameLoop = setInterval(() => game.update(), game.gameSpeed);